//package com.example.yichuangyun.service;
//
//import android.annotation.SuppressLint;
//import android.app.Notification;
//import android.app.NotificationChannel;
//import android.app.NotificationManager;
//import android.app.Service;
//import android.content.Context;
//import android.content.Intent;
//import android.database.Cursor;
//import android.net.Uri;
//import android.os.Build;
//import android.os.IBinder;
//import android.provider.CallLog;
//import android.telephony.PhoneStateListener;
//import android.telephony.TelephonyManager;
//import android.util.Log;
//
//import androidx.core.app.NotificationCompat;
//
//import com.example.yichuangyun.config.Constant;
//import com.example.yichuangyun.http.HttpRespond;
//import com.example.yichuangyun.http.MyObserver;
//import com.example.yichuangyun.http.RetrofitHelper;
//import com.example.yichuangyun.model.EventBusModel;
//import com.example.yichuangyun.utils.FileUtil;
//import com.example.yichuangyun.utils.ToastHelper;
//
//import org.greenrobot.eventbus.EventBus;
//import org.json.JSONException;
//import org.json.JSONObject;
//
//import java.io.File;
//import java.text.SimpleDateFormat;
//import java.util.Date;
//import java.util.List;
//import java.util.TimeZone;
//
//import okhttp3.MediaType;
//import okhttp3.MultipartBody;
//import okhttp3.RequestBody;
//
//public class PhoneService extends Service {
//    private static final String TAG = "@@@@@@@@PhoneService";
//    private final Uri callUri = CallLog.Calls.CONTENT_URI;
//    private final String[] columns = {CallLog.Calls.CACHED_NAME // 通话记录的联系人
//            , CallLog.Calls.NUMBER // 通话记录的电话号码
//            , CallLog.Calls.DATE // 通话记录的日期
//            , CallLog.Calls.DURATION // 通话时长
//            , CallLog.Calls.TYPE}; // 通话类型
//
//    private MyPhoneListener phoneListener;
//    //    private MyCallStateListener callStateListener;
//    private Context context;
//
//    private Notification notification;
////    private String lineNumber;
//
//    @Override
//    public IBinder onBind(Intent intent) {
//        // TODO Auto-generated method stub
//        return null;
//    }
//
//    @Override
//    public void onCreate() {
//        super.onCreate();
//        context = this;
//        // 8.0 以上需要特殊处理
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//            NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
//            nm.createNotificationChannel(new NotificationChannel("10", "App Service", NotificationManager.IMPORTANCE_DEFAULT));
//        }
//        NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "10");
//        notification = builder
//                .setContentText("service被设为前台进程！")
//                .setPriority(NotificationCompat.PRIORITY_MAX)
//                .setCategory(Notification.CATEGORY_SERVICE)
//                .build();
//    }
//
//    @Override
//    public int onStartCommand(Intent intent, int flags, int startId) {
//        Log.e(TAG, "服务启动了，开始监听电话服务状态");
////        TelephonyManager manager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
////        // Android12（sdk31）后，listen已经不能用了，需要使用registerTelephonyCallback来获取到来电状态
////        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
////            if (callStateListener == null) {
////                callStateListener = new MyCallStateListener();
////            }
////            manager.registerTelephonyCallback(getMainExecutor(), callStateListener);
////        } else {
////            if (phoneListener == null) {
////                phoneListener = new MyPhoneListener();
////            }
////            manager.listen(phoneListener, PhoneStateListener.LISTEN_CALL_STATE);
////        }
////        startForeground(2, notification);
////        return START_STICKY;
//        TelephonyManager manager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
//        // 为管理器设置监听器,监听电话的呼叫状态
//        if (phoneListener == null) {
//            phoneListener = new MyPhoneListener();
//        }
//        // TelephonyManager的listen函数在Android12过期了，如果没有授权READ_PHONE_STATE权限，此函数会抛出一个SecurityException。
//        manager.listen(phoneListener, PhoneStateListener.LISTEN_CALL_STATE);
//        startForeground(2, notification);
//        return START_STICKY;
//    }
//
////    @RequiresApi(api = Build.VERSION_CODES.S)
////    private class MyCallStateListener extends TelephonyCallback implements TelephonyCallback.CallStateListener {
////        private int label = -1;
////
////        @Override
////        public void onCallStateChanged(int state) {
////            // 防止调用多次
////            if (label != state) {
////                label = state;
////                switch (state) {
////                    case TelephonyManager.CALL_STATE_RINGING: // 零响状态1
////                        Log.e(TAG, "手机状态：来电");
////                        break;
////                    case TelephonyManager.CALL_STATE_OFFHOOK: // 通话状态2
////                        Log.e(TAG, "手机状态：接听");
////                        break;
////                    case TelephonyManager.CALL_STATE_IDLE: // 挂掉电话0
////                        Log.e("@@@@@@@@", Constant.isOpenMain + "====");
////                        if (!Constant.isOpenMain) {
////                            Log.e(TAG, "手机状态：空闲");
////                            new Thread(() -> {
////                                try {
////                                    // 延迟一秒，否则无法从本机获取当前这条通话记录
////                                    Thread.sleep(1000);
////                                    doUpload();
////                                } catch (InterruptedException e) {
////                                    e.printStackTrace();
////                                }
////                            }).start();
////                            break;
////                        }
////                        Constant.isOpenMain = false;
////                        break;
////                }
////            }
////        }
////    }
//
//    private final class MyPhoneListener extends PhoneStateListener {
//        private int label = -1;
//
//        @Override
//        public void onCallStateChanged(int state, String incomingNumber) {
//            try {
//                // 防止调用多次
//                if (label != state) {
//                    label = state;
//                    switch (state) {
//                        case TelephonyManager.CALL_STATE_RINGING: // 零响状态1
//                            Log.e(TAG, "手机状态：来电:" + incomingNumber);
//                            break;
//                        case TelephonyManager.CALL_STATE_OFFHOOK: // 通话状态2
//                            Log.e(TAG, "手机状态：接听");
//                            break;
//                        case TelephonyManager.CALL_STATE_IDLE:  // 挂掉电话0
////                            if (!Constant.isOpenMain) {
//                                Log.e(TAG, "手机状态：空闲");
//                                new Thread(() -> {
//                                    try {
//                                        // 延迟一秒，否则无法从本机获取当前这条通话记录
//                                        Thread.sleep(1000);
//                                        doUpload();
//                                    } catch (InterruptedException e) {
//                                        e.printStackTrace();
//                                    }
//                                }).start();
//                                break;
////                            }
////                            Constant.isOpenMain = false;
//                    }
//                }
//            } catch (IllegalStateException e) {
//                // TODO Auto-generated catch block
//                e.printStackTrace();
//            }
//            super.onCallStateChanged(state, incomingNumber);
//        }
//    }
//
//    private String mDate = "";
//
//    @SuppressLint({"SimpleDateFormat", "Range"})
//    private synchronized void doUpload() {
//        try {
//            // 当前时间毫秒数
//            long current = System.currentTimeMillis();
//            // 今天零点零分零秒的毫秒数
//            long zero = current / (1000 * 3600 * 24) * (1000 * 3600 * 24) - TimeZone.getDefault().getRawOffset();
//            // 只查当天的通话记录
//            Cursor cursor = context.getContentResolver().query(callUri, // 查询通话记录的URI
//                    columns, "date > ?", new String[]{String.valueOf(zero)}, CallLog.Calls.DEFAULT_SORT_ORDER// 按照时间逆序排列，最近打的最先显示
//            );
//            if (cursor != null && cursor.moveToFirst()) {
//                String name = cursor.getString(cursor.getColumnIndex(CallLog.Calls.CACHED_NAME));  //姓名
//                final String number = cursor.getString(cursor.getColumnIndex(CallLog.Calls.NUMBER));  //号码
//                final long dateLong = cursor.getLong(cursor.getColumnIndex(CallLog.Calls.DATE)); //获取通话日期
//                final String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(dateLong));
//                final int duration = cursor.getInt(cursor.getColumnIndex(CallLog.Calls.DURATION));//获取通话时长，值为多少秒
//                int type = cursor.getInt(cursor.getColumnIndex(CallLog.Calls.TYPE)); //获取通话类型：1.呼入2.呼出3.未接
//                Log.e("@@@@@type--->", type + ",   duration--->" + duration + ",   number--->" + number + "======" + date);
//                // 防止重复上传（同一时间的）
//                if (!mDate.equals(date)) {
//                    mDate = date;
//                    // 来电（呼入）
//                    if (type == 1 && duration == 0) { // 未接
//                        uploadCallRecord(number, 3, date, 0, 3, null);
//                    } else if (type == 1 && duration > 0) { // 已接
//                        alreadyLineUpload(number, date, duration, type);
//                    } else if (type == 3 || type == 5) { // 未接（3对方挂断，5本机挂断）
//                        uploadCallRecord(number, 3, date, 0, 3, null);
//                    } else if (type == 2) { // 去电
//                        if (duration > 0) { // 已接
//                            alreadyLineUpload(number, date, duration, type);
//                        } else { // 未接
//                            uploadCallRecord(number, 2, date, 0, type, null);
//                        }
//                    }
//                }
//            }
//        } catch (Exception e) {
//            Log.e("Exception", e.getMessage());
//        }
//    }
//
//    /**
//     * 上传通话录音文件
//     */
//    private void alreadyLineUpload(String number, String date, int duration, int type) {
//        List<File> files = FileUtil.searchFiles(FileUtil.getFile());
//        if (files.size() > 0) {
//            // 最大值下标，找到最新的录音文件
//            int maxIndex = 0;
//            for (int i = 0; i < files.size(); i++) {
//                // lastModified()：最后一次修改的时间
//                if (files.get(i).lastModified() > files.get(maxIndex).lastModified()) {
//                    maxIndex = i;
//                }
//            }
//            uploadCallRecord(number, 2, date, duration, type, files.get(maxIndex).getName().replaceAll(" +", "").contains(number) ? files.get(maxIndex) : null);
//        } else {
//            uploadCallRecord(number, 2, date, duration, type, null);
//        }
//    }
//
//    /**
//     * 上传通话记录
//     *
//     * @param telNumber 电话号码
//     * @param channel   渠道
//     * @param trackTime 通话时间
//     * @param callSec   通话时长
//     * @param callType  通话类型：1来电，2去电；3未接
//     * @param file      通话录音文件
//     */
//    private void uploadCallRecord(final String telNumber, int channel, final String trackTime, final Integer callSec, final Integer callType, final File file) {
//        Log.e("@@@@@@@@", file == null ? "file=null" : " file not null：" + file.getName());
//        long currentTime = System.currentTimeMillis();
//        JSONObject requestDate = new JSONObject();
//        try {
////            requestDate.put("lineNumber", lineNumber);
//            requestDate.put("telNumber", telNumber);
//            requestDate.put("channel", channel);
//            requestDate.put("trackTime", trackTime);
//            requestDate.put("linkedid", currentTime + telNumber); // 文件名
//            requestDate.put("callSec", callSec);
//            requestDate.put("callType", callType);
//            requestDate.put("serviceType", Constant.pushServiceType); // 默认1:商机，预留字段
//            requestDate.put("serviceId", Constant.pushBusinessId); // 发起拨号商机ID
//        } catch (JSONException e) {
//            e.printStackTrace();
//        }
//        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), requestDate.toString());
//        RetrofitHelper.getInstance().execute(RetrofitHelper.getService().uploadCallRecord(requestBody), new MyObserver<HttpRespond<String>>() {
//            @Override
//            protected void onSuccess(HttpRespond<String> stringHttpRespond) {
//                if (stringHttpRespond.code == Constant.SUCCESS) {
//                    ToastHelper.show("通话记录已成功上传");
//                    if (callSec > 0 && file != null) {
//                        uploadFile(file, currentTime + telNumber);
//                    }
//                    EventBus.getDefault().post(new EventBusModel(Constant.refreshTodayData));
//                } else {
//                    ToastHelper.show(stringHttpRespond.msg);
//                }
//                Constant.pushBusinessId = "";
//                Constant.pushServiceType = 1;
//            }
//
//            @Override
//            protected void onFail(Throwable e) {
//                super.onFail(e);
//                Constant.pushBusinessId = "";
//                Constant.pushServiceType = 1;
//            }
//        });
//    }
//
//    /**
//     * 上传录音文件
//     */
//    private void uploadFile(File file, String linkedId) {
//        RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
//        MultipartBody.Part part = MultipartBody.Part.createFormData("file", linkedId, requestBody);
//        RetrofitHelper.getInstance().execute(RetrofitHelper.getService().uploadRecordFile(part), new MyObserver<HttpRespond<String>>() {
//            @Override
//            protected void onSuccess(HttpRespond<String> stringHttpRespond) {
//                if (Constant.SUCCESS == stringHttpRespond.code) {
//                    ToastHelper.show("录音文件已成功上传");
//                    file.delete();
//                } else {
//                    ToastHelper.show(stringHttpRespond.msg);
//                }
//            }
//
//            @Override
//            protected void onFail(Throwable e) {
//                super.onFail(e);
//                ToastHelper.show(e.getMessage());
//            }
//        });
//    }
//
//    @Override
//    public void onDestroy() {
//        super.onDestroy();
//        stopForeground(true);
//    }
//}
//
